﻿using System;
using System.Collections.Generic;
using System.Threading;
using AsyncLibrary;

namespace AsycnLibraryTest
{
  public class UpdateItemOperation : AsyncOperation
  {
    private readonly string _item;

    public UpdateItemOperation(string item)
    {
      _item = item;
    }

    protected override void RunCore()
    {
      StatusSpeaker.SetInfo("Updating: " + _item);
      if (_item.Contains("3")) throw new Exception(_item + " operation error");
      Thread.Sleep(155);
    }
  }

  public class UpdateItemsOperation : AsyncOperation
  {
    private readonly List<string> _items;

    public event Action<string> OnError;

    public UpdateItemsOperation(List<string> items)
    {
      _items = items;
    }

    protected override void RunCore()
    {
      StatusSpeaker.InfinitMode("Preparing data...");

      var message = string.Format("Updating {0} items", _items.Count);
      StatusSpeaker.FinitMode(message, _items.Count);
      foreach (var item in _items)
      {
        var updateItemOperation = new UpdateItemOperation(item);
        updateItemOperation.StatusListeners.AddRange(StatusListeners);
        updateItemOperation.Run(new OperationContext());
        StatusSpeaker.IncrementProgress();
      }
    }

    protected override void OnOperationFinished()
    {
      if (!string.IsNullOrEmpty(Error))
        RaiseOnError(Error);
      base.OnOperationFinished();
    }

    private void RaiseOnError(string error)
    {
      var handler = OnError;
      if (handler != null) handler(error);
    }

  }
}